package com.gosdk.p;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.widget.Toast;

public class AppManager {

    public static boolean isAppInstalled(Context paramContext, String packageName, List<PackageInfo> packageList) {
        
        Iterator<PackageInfo> localIterator = packageList.iterator();

        while (localIterator.hasNext()) {
            if (localIterator.next().packageName.equalsIgnoreCase(packageName))
                return true;
        }

        return false;
    }

    public static boolean isAppInstalled(Context paramContext, String packageName) {
        List<PackageInfo> packageList = paramContext.getPackageManager().getInstalledPackages(0);
        Iterator<PackageInfo> localIterator = packageList.iterator();

        while (localIterator.hasNext()) {
            if (localIterator.next().packageName.equalsIgnoreCase(packageName))
                return true;
        }

        return false;
    }
    
    public static void InstallApplication(Context context, String filepath) {
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);

        intent.setDataAndType(Uri.fromFile(new File(filepath)),
                "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        
        Toast.makeText(context, "install", Toast.LENGTH_LONG).show();
    }

    public static void openApp(String packageName, Context context) throws Exception {
        PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0);

        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(pi.packageName);

        List<ResolveInfo> apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0);

        ResolveInfo ri = apps.iterator().next();

        if (ri != null) {
            String className = ri.activityInfo.name;

            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            ComponentName cn = new ComponentName(packageName, className);

            intent.setComponent(cn);
            context.startActivity(intent);

        }

    }

    public static void openApp2(String packageName, Context context) {
        Intent intent1 = new Intent();
        PackageManager pm = context.getPackageManager();
        intent1 = pm.getLaunchIntentForPackage(packageName);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);
    }
}
